package com.jinlejia.erp.base;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.utils.ACache;
import com.utils.MD5Utils;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Random;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 2017/3/3 0003.
 */

public class TokenInterceptor implements Interceptor {
    private Context context;

    public TokenInterceptor(Context c) {
        this.context = c;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if ("www.pgyer.com".equals(request.url().host())|| //如果是蒲公英，则不进行拦截
            "api.weixin.qq.com".equals(request.url().host())){  //如果是微信，则不进行拦截
            return chain.proceed(request);
        }
        Response response = chain.proceed(request);
        MediaType contentType = response.body().contentType();
        //response string()方法被调用，响应被消耗
        String bodyString = response.body().string();
        if( isJson(bodyString) && !TextUtils.isEmpty(bodyString)) {
            if (JSON.parseObject(bodyString).getString("code").equals("900")) { //根据和服务端的约定判断token过期
                //同步请求方式，获取最新的Token
                String newSession = getToken();
                if (TextUtils.isEmpty(newSession)){
                    newSession = "";
                }
                //使用新的Token，创建新的请求
                Request newRequest = chain.request()
                        .newBuilder()
                        .header("token", newSession)
                        .build();
                //重新请求
                return chain.proceed(newRequest);
            } else {
                //重建response
                ResponseBody body = ResponseBody.create(contentType, bodyString);
                return response.newBuilder().body(body).build();
            }
        }else{
            //不是JSON格式
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message","数据格式异常!");
            jsonObject.put("code","1001");
            ResponseBody body = ResponseBody.create(contentType, jsonObject.toJSONString());
            return response.newBuilder().body(body).build();
        }
    }


    public String getToken() {

        OkHttpClient okHttpClient  = OkHttpUtils.getInstance().getOkHttpClient();
        JSONObject jsonObject = new JSONObject();
        Class clazz;
        String appPin = null;
        try {
            clazz = Class.forName("com.jinlejia.erp.base.IApplication");
            Method method = clazz.getMethod("getRegistrationID");
            appPin = String.valueOf(method.invoke(null));
        } catch (Exception ignored) {
        }
        jsonObject.put("app_pin", appPin);
        jsonObject.put("appId", "8528745b03a2418b9fea3a6319df4da5");

        jsonObject.put("secret", MD5Utils.md5((new Random().nextInt(9999) + "android" + System.currentTimeMillis())));

        String json = jsonObject.toJSONString();

        //MediaType  设置Content-Type 标头中包含的媒体类型值
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);

        Request request = new Request.Builder()
                .url(ApiConfig.TOKEN)//请求的url
                .post(requestBody)
                .build();

        //创建/Call
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            JSONObject obj = JSON.parseObject(response.body().string());
            if ( obj.getString("code").equals("200") )
                ACache.get(context).put("token", obj.getString("data"),60*60*2);
            return  obj.getString("data");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 判断是否是json结构
     */
    public boolean isJson(String value) {
        try {
            JSON.parse(value);
        } catch (JSONException e) {
            return false;
        }
        return true;
    }

//    public static String convertStreamToString(InputStream is) {
//
//        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//        StringBuilder sb = new StringBuilder();
//
//        String line = null;
//        try {
//            while ((line = reader.readLine()) != null) {
//                sb.append(line + "\n");
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                is.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//
//        return sb.toString();
//    }

}
